/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.batch.web.ProductDelayBatchUpdateAction
   Module Description   :

   Date Created      : 2011/2/14
   Original Author   : jeffma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.batch.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.batch.entity.BatchDetail;
import com.yaodian100.ec.batch.entity.BatchEvent;
import com.yaodian100.ec.batch.service.BatchEventService;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;

/**
 * @author jeffma
 * 
 */
public class ProductDelayBatchUpdateAction extends AbstractUpdateAction {

	/** serialVersionUID */
	private static final long serialVersionUID = -2546112236545463765L;

	@Autowired
	private ProductService productService;
	@Autowired
	private BatchEventService batchEventService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private TemplateService velocityService;
	private String paramProductId;
	private String paramProductName;
	private String paramProductType;
	private String paramProductAttr;
	private String paramProductIsScm;
	private String paramSupplierId;
	private String paramBrand;
	private String paramCategoryL1;
	private String paramCategoryL2;
	private String paramCategoryL3;
	private String paramCategoryL4;
	private String paramHasShelf;
	private InputStream fileInputStream;
	private String paramBatchEventId;
	private int paramDeliveryDay = 0;
	private String paramUseDeliveryDay = "N";
	private boolean paramExecuteNow = false;
	private String paramStartDate;
	private String paramStartTime;

	private String dataoldornew;
	private File upload;
	private String uploadContentType;
	private String uploadFileName;
	private List<String> excelId;
	private List<String> errId;
	private List<BatchDetail> deldetail;

	private List<Product> products = new ArrayList();
	private Map<String, BigDecimal> shelfMap = new HashMap();
	private Map<Integer, String> productCategory = new HashMap();
	private Menu menuProductType;
	private Menu menuProductAttr;
	private Menu menuProductIsScm;
	private List menuCategoryLevel1List;
	private List menuCategoryLevel2List;
	private List menuCategoryLevel3List;
	private List menuCategoryLevel4List;
	private Map<String, Brand> menuBrand;
	private Option productDelayOption;
	private String tmpUseDeliveryDay = "N";
	private String tmpDeliveryDay = "0";
	private String prodSortBy = "productId";
	private String prodSortByType = "desc";
	private String excelPath = "productdelaybatchupdate.xls";
	private int uploadErr = 0;
	private int uploadSuccess = 0;
	private String step2Upload = null;

	/**
	 * 新建立批次
	 * 
	 * @return
	 */
	public String create() {
		shelfMap.clear();
		products.clear();
		getParamSelectArray().clear();
		getPager().setTotalSize(0);
		paramBatchEventId = null;
		tmpUseDeliveryDay = "N";
		tmpDeliveryDay = "0";
		setEvent(new BatchEvent(productDelayOption));
		getDetailMap().clear();

		countSelect();
		return "step1";
	}

	/**
	 * 修改批次(已存档)
	 * 
	 * @return
	 */
	public String select() {
		if (StringUtils.isNotBlank(paramBatchEventId)) {
			setEvent(batchEventService.get(paramBatchEventId));
			if (getEvent() != null) {
				getDetailMap().clear();
				List<BatchDetail> detailList = batchEventService.getDetails(paramBatchEventId);
				for (BatchDetail detail : detailList) {
					getDetailMap().put(detail.getDataKey(), detail);
				}
			} else {
				addActionError("批次不存在");
				return list();
			}
		} else {
			addActionError("批次不存在");
			return list();
		}
		countSelect();
		return "step1";
	}

	/**
	 * 新增批次时, 搜寻商品
	 * 
	 * @return
	 */
	public String search() {
		shelfMap.clear();
		products.clear();
		getParamSelectArray().clear();
		getDetailMap().clear();
		getPager().setTotalSize(0);

		paramBatchEventId = null;

		searchProduct();
		countSelect();
		return "step1";
	}

	private void searchProduct() {
		Map eqData = new HashMap();
		Map neData = new HashMap();
		Map inData = new HashMap();
		if (StringUtils.isNotBlank(paramProductIsScm)) {
			eqData.put("isScm", paramProductIsScm);
		} else {
			neData.put("isScm", "N");
		}
		if (StringUtils.isNotBlank(paramProductType)) {
			eqData.put("productType", Integer.valueOf(paramProductType).intValue());
		} else {
			inData.put("productType", Arrays.asList(0, 1));
		}
		if (StringUtils.isNotBlank(paramProductAttr)) {
			eqData.put("isDelete", paramProductAttr);
		}
		if (StringUtils.isNotBlank(paramSupplierId)) {
			eqData.put("supplierId", paramSupplierId);
		}
		if (StringUtils.isNotBlank(paramBrand)) {
			eqData.put("productBrand", paramBrand);
		}

		Boolean hasShelf = null;
		if (StringUtils.isNotBlank(paramHasShelf)) {
			hasShelf = Boolean.valueOf(paramHasShelf);
		}
		StringBuffer prarmCategoryPath = new StringBuffer();
		if (StringUtils.isNotBlank(paramCategoryL1)) {
			prarmCategoryPath.append(paramCategoryL1).append("/");
			if (StringUtils.isNotBlank(paramCategoryL2)) {
				prarmCategoryPath.append(paramCategoryL2).append("/");
				if (StringUtils.isNotBlank(paramCategoryL3)) {
					prarmCategoryPath.append(paramCategoryL3).append("/");
					if (StringUtils.isNotBlank(paramCategoryL4)) {
						prarmCategoryPath.append(paramCategoryL4).append("/");
					}
				}
			}
		}
		List productIds = null;
		if (StringUtils.isNotBlank(paramProductId)) {
			paramProductId = StringUtils.remove(paramProductId, " ");
			paramProductId = StringUtils.remove(paramProductId, "\n");
			String[] pIds = StringUtils.split(paramProductId, ",");
			productIds = new ArrayList();
			for (String p : pIds) {
				productIds.add(p);
			}
		}
		long entitySize = productService.getProductAttrListSize(productIds, paramProductName, null,
				prarmCategoryPath.toString(), eqData, neData, inData, hasShelf).longValue();
		getPager().setTotalSize(entitySize);

		for (Product p : products) {
			if (getDetailMap().keySet().contains(p.getProductId())
					&& "false".equals(getParamSelectArray().get(p.getProductId()))) {
				getDetailMap().remove(p.getProductId());
			} else if (!getDetailMap().keySet().contains(p.getProductId())
					&& "true".equals(getParamSelectArray().get(p.getProductId()))) {
				BatchDetail detail = productToDetail(p);
				getDetailMap().put(p.getProductId(), detail);
			}
		}

		products.clear();
		List<Object[]> productShelf = productService.getProductAttrList(productIds, paramProductName, prarmCategoryPath
				.toString(), eqData, neData, inData, hasShelf, getPager().getCurrentPage() * getPager().getPageRecord(),
				getPager().getPageRecord(), new String[] { prodSortBy + " " + prodSortByType, "productId desc" });
		for (Object[] o : productShelf) {
			Product p = (Product) o[1];
			products.add(p);
			if (getParamSelectArray().get(p.getProductId()) == null) {
				getParamSelectArray().put(p.getProductId(), "false");
			}
			shelfMap.put(p.getProductId(), (BigDecimal) o[0]);
			if (productCategory.get(Integer.valueOf(p.getMainCategoryID())) == null) {
				productCategory.put(Integer.valueOf(p.getMainCategoryID()), categoryService.makeCategorieURL(Long.valueOf(p
						.getMainCategoryID()), false));
			}
		}
	}

	/**
	 * 新增批次时, 换页
	 * 
	 * @return
	 */
	public String changePage() {
		searchProduct();
		countSelect();
		return "step1";
	}

	/**
	 * 新增批次时, 选取全部
	 * 
	 * @return
	 */
	public String selectAll() {
		Map eqData = new HashMap();
		Map neData = new HashMap();
		Map inData = new HashMap();
		if (StringUtils.isNotBlank(paramProductIsScm)) {
			eqData.put("isScm", paramProductIsScm);
		} else {
			neData.put("isScm", "N");
		}
		if (StringUtils.isNotBlank(paramProductType)) {
			eqData.put("productType", Integer.valueOf(paramProductType).intValue());
		} else {
			inData.put("productType", Arrays.asList(0, 1));
		}
		if (StringUtils.isNotBlank(paramProductAttr)) {
			eqData.put("isDelete", paramProductAttr);
		}
		if (StringUtils.isNotBlank(paramSupplierId)) {
			eqData.put("supplierId", paramSupplierId);
		}
		if (StringUtils.isNotBlank(paramBrand)) {
			eqData.put("productBrand", paramBrand);
		}

		Boolean hasShelf = null;
		if (StringUtils.isNotBlank(paramHasShelf)) {
			hasShelf = Boolean.valueOf(paramHasShelf);
		}
		StringBuffer prarmCategoryPath = new StringBuffer();
		if (StringUtils.isNotBlank(paramCategoryL1)) {
			prarmCategoryPath.append(paramCategoryL1).append("/");
			if (StringUtils.isNotBlank(paramCategoryL2)) {
				prarmCategoryPath.append(paramCategoryL2).append("/");
				if (StringUtils.isNotBlank(paramCategoryL3)) {
					prarmCategoryPath.append(paramCategoryL3).append("/");
					if (StringUtils.isNotBlank(paramCategoryL4)) {
						prarmCategoryPath.append(paramCategoryL4).append("/");
					}
				}
			}
		}
		List productIds = null;
		if (StringUtils.isNotBlank(paramProductId)) {
			paramProductId = StringUtils.remove(paramProductId, " ");
			paramProductId = StringUtils.remove(paramProductId, "\n");
			String[] pIds = StringUtils.split(paramProductId, ",");
			productIds = new ArrayList();
			for (String p : pIds) {
				productIds.add(p);
			}
		}

		List<Object[]> productShelf = productService.getProductAttrList(productIds, paramProductName, prarmCategoryPath
				.toString(), eqData, neData, inData, hasShelf, 0, -1, null);
		for (Object[] o : productShelf) {
			Product p = (Product) o[1];
			getParamSelectArray().put(p.getProductId(), "true");
			if (getDetailMap().get(p.getProductId()) == null) {
				BatchDetail detail = productToDetail(p);
				getDetailMap().put(p.getProductId(), detail);
			}
		}
		countSelect();
		return "step1";
	}

	public String uploadFile() throws Exception {
		uploadSuccess = 0;
		uploadErr = 0;
		step2Upload = null;
		errId = null;
		if (!uploadFileName.startsWith("productDelayBatchUpdate")) {
			addActionError("你上传的档案名为「" + uploadFileName + "」，与下载的档案名不符，请检查档案是否正确");
			return "step2";
		}
		SAXReader reader = new SAXReader();
		String file = FileUtils.readFileToString(upload).replace("&", " ");
		FileUtils.writeStringToFile(upload, file);
		Element root = null;
		Element tableEle = null;
		Element workEle = null;
		excelId = new ArrayList<String>();
		for (Map.Entry<String, BatchDetail> list : getDetailMap().entrySet()) {
			excelId.add(list.getKey());
		}

		try {
			Document doc = reader.read(upload);
			root = doc.getRootElement();
			workEle = (Element) root.elementIterator("Worksheet").next();
			tableEle = (Element) workEle.elementIterator("Table").next();
		} catch (Exception e) {
			addActionError("档案上传失败:" + e.getMessage());
			return "step2";
		}
		int row = 0;
		List<String> idlist = new ArrayList<String>();
		List<String> errIdList = new ArrayList<String>();
		deldetail = new ArrayList<BatchDetail>();
		errId = new ArrayList<String>();
		try {
			for (Iterator r = tableEle.elementIterator("Row"); r.hasNext();) {
				List<String> cellList = new ArrayList<String>();
				row++;
				Element rowEle = (Element) r.next();
				if (row > 1) {
					int cellNo = 0;
					boolean eq = false;
					String udd = null;
					for (Iterator c = rowEle.elementIterator("Cell"); c.hasNext();) {
						cellNo++;
						Element cellEle = (Element) c.next();
						if (cellNo == 1) {
							int keyeq = 0;
							for (String oldId : excelId) {
								if (oldId.matches(cellEle.getStringValue())) {
									keyeq++;
								}
							}
							if (keyeq > 0) {
								eq = true;
								idlist.add(cellEle.getStringValue());
								cellList.add(cellEle.getStringValue());
							} else {
								eq = false;
								cellList.add(cellEle.getStringValue());
							}
						}
						if (cellNo == 7 && eq == true) {
							if (cellEle.getStringValue().trim().toUpperCase().equals("Y")
									|| cellEle.getStringValue().trim().toUpperCase().equals("N")) {
								eq = true;
								cellList.add(cellEle.getStringValue().toUpperCase());
								udd = cellEle.getStringValue().trim().toUpperCase();
							} else {
								eq = false;
							}
						}
						if (cellNo == 8 && eq == true) {
							if (udd.equals("Y")) {
								if (cellEle.getStringValue().trim().matches("^[0-9]*[0-9][0-9]*$")) {
									eq = true;
									cellList.add(cellEle.getStringValue());
								} else {
									eq = false;
								}
							}
							if (udd.equals("N")) {
								if (cellEle.getStringValue().trim().equals("0")) {
									eq = true;
									cellList.add(cellEle.getStringValue());
								} else {
									eq = false;
								}
							}
						}
					}
					// 存取失败编号
					if (eq == false && cellList != null) {
						errIdList.add(cellList.get(0));
					}
					// 资料栏位核对无误后更新资料
					if (eq == true && cellList != null) {
						if (excelToDetail(cellList)) {
							uploadSuccess++;
						}
					}
				}
			}
		} catch (Exception e) {
			addActionError("上传的资料存取失败，请重新选择下载编辑" + e.getMessage());
			return "step2";
		}
		try {
			// 从detailMap中删除已被删除的商品
			if (idlist != null) {
				for (String oldId : excelId) {
					int eq = 0;
					for (String newpid : idlist) {
						if (oldId.contains(newpid)) {
							eq++;
						}
					}
					if (eq == 0) {
						deldetail.add(getDetailMap().get(oldId));
						getDetailMap().remove(oldId);
					}
				}
			}
			if (row > 1) {
				uploadErr = (row - 1) - uploadSuccess;
			}
			// 取前20笔失败编号
			if (errIdList.size() >= 20) {
				for (int i = 0; i < 20; i++) {
					errId.add(errIdList.get(i));
				}
			}
			if (errIdList.size() < 20) {
				for (String errid : errIdList) {
					errId.add(errid);
				}
			}
			step2Upload = "uploadok";
		} catch (Exception e) {
			addActionError("檔案错误:" + e.getMessage());
		}

		return "step2";
	}

	private boolean excelToDetail(List<String> excelLists) {
		boolean upload = false;
		BatchDetail detailNew = null;
		if (excelLists != null && excelLists.size() == 3) {
			try {
				detailNew = getDetailMap().get(excelLists.get(0).trim());
				if (detailNew != null) {
					detailNew.getDataNewMap().put("useDeliveryDay", excelLists.get(1).trim());
					detailNew.getDataNewMap().put("deliveryDay", excelLists.get(2).trim());
					getDetailMap().put(excelLists.get(0).trim(), detailNew);
					upload = true;
				}

			} catch (Exception e) {
				e.printStackTrace();
				addActionError("资料更新失败:" + e.getMessage());
				upload = false;
			}
		}
		return upload;
	}

	private void countSelect() {
		int count = 0;
		for (String s : getParamSelectArray().values()) {
			if ("true".equals(s)) {
				count++;
			}
		}
		ServletActionContext.getRequest().setAttribute("selectSize", count);
	}

	/**
	 * 新增 or 修改 details 的值
	 * 
	 * @return
	 */
	public String edit() {
		uploadSuccess = 0;
		uploadErr = 0;
		step2Upload = null;
		errId = null;
		if (getEvent() != null && getEvent().getModifyDate() == null && StringUtils.isBlank(paramBatchEventId)) {
			// 新增
			for (Product p : products) {
				if (getDetailMap().keySet().contains(p.getProductId())
						&& "false".equals(getParamSelectArray().get(p.getProductId()))) {
					getDetailMap().remove(p.getProductId());
				} else if (!getDetailMap().keySet().contains(p.getProductId())
						&& "true".equals(getParamSelectArray().get(p.getProductId()))) {
					BatchDetail detail = productToDetail(p);
					getDetailMap().put(p.getProductId(), detail);
				}
			}
		} else if (getEvent() != null && getEvent().getModifyDate() != null) {
			// 修改
			setEvent(batchEventService.get(paramBatchEventId));
			if (getEvent() != null) {
				getDetailMap().clear();
				List<BatchDetail> detailList = batchEventService.getDetails(paramBatchEventId);
				for (BatchDetail detail : detailList) {
					getDetailMap().put(detail.getDataKey(), detail);
				}
			}
			if (checkEditable() == false) {
				return list();
			}
		} else if (StringUtils.isNotBlank(paramBatchEventId)) {
			// 修改
			setEvent(batchEventService.get(paramBatchEventId));
			if (getEvent() != null) {
				getDetailMap().clear();
				List<BatchDetail> detailList = batchEventService.getDetails(paramBatchEventId);
				for (BatchDetail detail : detailList) {
					getDetailMap().put(detail.getDataKey(), detail);
				}
			}
			if (checkEditable() == false) {
				return list();
			}
		} else {
			addActionError("批次不存在");
			return list();
		}
		return "step2";
	}

	private void creatExcel(Map<String, BatchDetail> detailMap) {
		File checkfile = new File(excelPath);
		try {
			Map<String, Object> excelContent = new HashMap<String, Object>();
			excelContent.put("detailMap", detailMap);
			excelContent.put("detailMapSize", detailMap.size() + 1);
			excelContent.put("dataoldornew", dataoldornew);
			excelContent.put("tmpUseDeliveryDay", tmpUseDeliveryDay);
			excelContent.put("tmpDeliveryDay", tmpDeliveryDay);
			String fileContent = velocityService.format("productDelayBatch", excelContent);
			FileUtils.writeStringToFile(checkfile, fileContent);
		} catch (Exception e) {
			addActionError("Excel档错误:" + e.getMessage());
		}
	}

	private BatchDetail productToDetail(Product p) {
		BatchDetail detail = null;
		try {
			detail = new BatchDetail(getEvent());
			detail.setDataKey(p.getProductId());
			detail.getDataOldMap().put("productName", p.getProductName());
			detail.getDataOldMap().put("supplierId", p.getSupplierId());
			if (productCategory.get(Integer.valueOf(p.getMainCategoryID())) == null) {
				detail.getDataOldMap().put("mainCategoryPathDesc",
						categoryService.makeCategorieURL(Long.valueOf(p.getMainCategoryID()), false));
			} else {
				detail.getDataOldMap().put("mainCategoryPathDesc", productCategory.get(Integer.valueOf(p.getMainCategoryID())));
			}
			Option productTypeOption = menuProductType.getOptions().get(String.valueOf(p.getProductType()));
			if (productTypeOption != null) {
				detail.getDataOldMap().put("productType", productTypeOption.getName());
			} else {
				detail.getDataOldMap().put("productType", String.valueOf(p.getProductType()));
			}
			detail.getDataOldMap().put("isScm", menuProductIsScm.getOptions().get(p.getIsScm()).getName());
			detail.getDataOldMap().put("deliveryDay", String.valueOf(p.getDeliveryDay()));
			detail.getDataOldMap().put("useDeliveryDay", p.getUseDeliveryDay());
			detail.getDataNewMap().put("useDeliveryDay", "N");
			detail.getDataNewMap().put("deliveryDay", "0");
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("系统错误, MSG:" + e.getMessage());
			detail = null;
		}
		return detail;
	}

	/**
	 * 新增 or 修改 确认资料
	 * 
	 * @return
	 */
	public String confirm() {
		if (checkEditable() == false) {
			return list();
		}
		try {
			// 誤會 struts 錯誤, 改成手動更新資料.
			HttpServletRequest request = ServletActionContext.getRequest();
			Enumeration<String> enu = request.getParameterNames();
			while (enu.hasMoreElements()) {
				String reqkey = enu.nextElement();
				String value = request.getParameter(reqkey);
				if (reqkey.startsWith("detailMap") && reqkey.indexOf("_") != -1) {
					String s[] = StringUtils.split(reqkey, "_");
					String dataKey = s[1];
					String dataAttr = s[2];
					BatchDetail detail = getDetailMap().get(dataKey);
					detail.getDataNewMap().put(dataAttr, value);
					getDetailMap().put(dataKey, detail);
					logger.debug("detail:{} / {} / {}", new Object[] { detail, value, detail.getDataNew() });
				}
			}
			getPager().setTotalSize(getDetailMap().size());
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("系统错误, MSG:" + e.getMessage());
			return "step2";
		}

		return "step3";
	}

	/**
	 * 新增 or 修改 存档
	 * 
	 * @return
	 */
	public String done() {
		if (checkEditable() == false) {
			return list();
		}
		try {
			if (paramExecuteNow) {
				getEvent().setStartDate(DateUtil.getCurrentTime());
			} else {
				Calendar now = Calendar.getInstance();
				if (StringUtils.isBlank(paramStartDate)) {
					addFieldError("paramStartTime", "请选择预约日期时间");
					return "step3";
				} else if (StringUtils.isBlank(paramStartTime)) {
					addFieldError("paramStartTime", "请选择预约日期时间");
					return "step3";
				} else {
					Date paramStartDT = DateUtil.convertStringToDate(DateUtil.PATTERN_DATE_TIME, paramStartDate + " "
							+ paramStartTime);
					if (now.getTime().after(paramStartDT)) {
						addFieldError("paramStartTime", "已超过你所预约的时间，你可以重新选择预约时间或选择立即执行");
						return "step3";
					} else {
						getEvent().setStartDate(paramStartDT);
					}
				}
			}
			getEvent().setStatus(BatchEvent.Status.FINISH);
			getEvent().setRecordSize(getDetailMap().size());
			batchEventService.save(getEvent());
			batchEventService.saveOrUpdateDetails(getDetailMap().values());
			if (deldetail != null) {
				batchEventService.deleteDetails(deldetail);
			}
			setEvent(null);
			getDetailMap().clear();
			paramBatchEventId = null;
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("系统错误, MSG:" + e.getMessage());
			return "step3";
		}
		return list();
	}

	public String downloadFile() throws Exception {
		try {
			uploadSuccess = 0;
			uploadErr = 0;
			step2Upload = null;
			errId = null;
			creatExcel(getDetailMap());
			fileInputStream = new FileInputStream(excelPath);
		} catch (Exception e) {
			addActionError("资料下载失败，请回到上一步重新选取资料");
			return "step2";
		}
		return SUCCESS;
	}

	private boolean checkEditable() {
		if (StringUtils.isNotBlank(paramBatchEventId) && getEvent() != null) {
			if (StringUtils.isNotBlank(getEvent().getOid()) && !paramBatchEventId.equals(getEvent().getOid())) {
				addActionError("批次资料错误, 多视窗操作. 请重新选取.");
				setEvent(null);
				paramBatchEventId = null;
			}
			if (!getDetailMap().isEmpty()) {
				String oid = getDetailMap().values().iterator().next().getBatchEvent().getOid();
				if (StringUtils.isNotBlank(oid) && !oid.equals(paramBatchEventId)) {
					addActionError("批次资料错误, 多视窗操作. 请重新选取.");
					setEvent(null);
					paramBatchEventId = null;
				}
			}
		}
		if (getEvent() != null && !getEvent().isEditable()) {
			// 检核允许编辑条件
			addActionError("与排程时间邻近5分钟, 无法修改");
		}
		if (getEvent() == null) {
			addActionError("批次不存在");
		}

		if (hasActionErrors()) {
			return false;
		} else {
			return true;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.batch.web.CommonBatchAction#view()
	 */
	@Override
	public String view() {
		shelfMap.clear();
		products.clear();
		getParamSelectArray().clear();
		getPager().setTotalSize(0);

		List failDataKey = new ArrayList();
		if (StringUtils.isNotBlank(getBatchEventId())) {
			List<BatchDetail> details = batchEventService.getDetails(getBatchEventId());
			getParamSelectArray().clear();
			for (BatchDetail d : details) {
				getParamSelectArray().put(d.getDataKey(), "true");
				if (Boolean.FALSE.equals(d.getExecuteStatus())) {
					failDataKey.add(d.getDataKey());
				}
			}
		}
		ServletActionContext.getRequest().setAttribute("failDataKey", StringUtils.join(failDataKey, ", "));
		return super.view();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.batch.web.CommonBatchAction#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		super.prepare();
		if (menuProductType == null) {
			menuProductType = menuService.get("Product.Type").clone();
			if (menuProductType.getOptions().get("7") == null) {
				menuProductType.addOption("7", "立即购买");
			}
		}
		if (menuProductAttr == null) {
			menuProductAttr = menuService.get("Product.Attribute");
		}
		if (menuProductIsScm == null) {
			menuProductIsScm = menuService.get("Product.isScm");
		}
		if (menuBrand == null) {
			CommonCriteria cri = new CommonCriteria();
			List<Brand> brands = productService.getBrandList(0, -1, cri, null);
			menuBrand = new HashMap();
			for (Brand b : brands) {
				menuBrand.put(b.getBrandId(), b);
			}
		}

		if (menuCategoryLevel1List == null) {
			menuCategoryLevel1List = categoryService.getAvailableChild(0L);
		}
		if (StringUtils.isNotBlank(paramCategoryL1)) {
			menuCategoryLevel2List = categoryService.getAvailableChild(Long.valueOf(paramCategoryL1));
		}
		if (StringUtils.isNotBlank(paramCategoryL2)) {
			menuCategoryLevel3List = categoryService.getAvailableChild(Long.valueOf(paramCategoryL2));
		}
		if (StringUtils.isNotBlank(paramCategoryL3)) {
			menuCategoryLevel4List = categoryService.getAvailableChild(Long.valueOf(paramCategoryL3));
		}

		if (productDelayOption == null) {
			Menu menuBatch = menuService.get("BatchEvent.name");
			productDelayOption = menuBatch.getOptions().get("product/delay");
		}
	}

	/**
	 * @return the shelfs
	 */
	public Map<String, BigDecimal> getShelfMap() {
		return shelfMap;
	}

	/**
	 * @return the productCategory
	 */
	public Map<Integer, String> getProductCategory() {
		return productCategory;
	}

	/**
	 * @return the menuBrand
	 */
	public Map<String, Brand> getMenuBrand() {
		return menuBrand;
	}

	/**
	 * @return the paramExecuteNow
	 */
	public boolean isParamExecuteNow() {
		return paramExecuteNow;
	}

	/**
	 * @param paramExecuteNow the paramExecuteNow to set
	 */
	public void setParamExecuteNow(boolean paramExecuteNow) {
		this.paramExecuteNow = paramExecuteNow;
	}

	/**
	 * @return the prodSortBy
	 */
	public String getProdSortBy() {
		return prodSortBy;
	}

	/**
	 * @param prodSortBy the prodSortBy to set
	 */
	public void setProdSortBy(String prodSortBy) {
		this.prodSortBy = prodSortBy;
	}

	/**
	 * @return the prodSortByType
	 */
	public String getProdSortByType() {
		return prodSortByType;
	}

	/**
	 * @param prodSortByType the prodSortByType to set
	 */
	public void setProdSortByType(String prodSortByType) {
		this.prodSortByType = prodSortByType;
	}

	/**
	 * @return the paramStartDate
	 */
	public String getParamStartDate() {
		return paramStartDate;
	}

	/**
	 * @param paramStartDate the paramStartDate to set
	 */
	public void setParamStartDate(String paramStartDate) {
		this.paramStartDate = paramStartDate;
	}

	/**
	 * @return the paramStartTime
	 */
	public String getParamStartTime() {
		return paramStartTime;
	}

	/**
	 * @param paramStartTime the paramStartTime to set
	 */
	public void setParamStartTime(String paramStartTime) {
		this.paramStartTime = paramStartTime;
	}

	/**
	 * @return the paramBatchEventId
	 */
	public String getParamBatchEventId() {
		return paramBatchEventId;
	}

	/**
	 * @param paramBatchEventId the paramBatchEventId to set
	 */
	public void setParamBatchEventId(String paramBatchEventId) {
		this.paramBatchEventId = paramBatchEventId;
	}

	/**
	 * @return the paramDeliveryDay
	 */
	public int getParamDeliveryDay() {
		return paramDeliveryDay;
	}

	/**
	 * @param paramDeliveryDay the paramDeliveryDay to set
	 */
	public void setParamDeliveryDay(int paramDeliveryDay) {
		this.paramDeliveryDay = paramDeliveryDay;
	}

	/**
	 * @return the paramUseDeliveryDay
	 */
	public String getParamUseDeliveryDay() {
		return paramUseDeliveryDay;
	}

	/**
	 * @param paramUseDeliveryDay the paramUseDeliveryDay to set
	 */
	public void setParamUseDeliveryDay(String paramUseDeliveryDay) {
		this.paramUseDeliveryDay = paramUseDeliveryDay;
	}

	/**
	 * @return the paramProductId
	 */
	public String getParamProductId() {
		return paramProductId;
	}

	/**
	 * @param paramProductId the paramProductId to set
	 */
	public void setParamProductId(String paramProductId) {
		this.paramProductId = paramProductId;
	}

	/**
	 * @return the menuProductType
	 */
	public Menu getMenuProductType() {
		return menuProductType;
	}

	/**
	 * @return the menuProductAttr
	 */
	public Menu getMenuProductAttr() {
		return menuProductAttr;
	}

	/**
	 * @return the menuProductIsScm
	 */
	public Menu getMenuProductIsScm() {
		return menuProductIsScm;
	}

	/**
	 * @return the paramProductName
	 */
	public String getParamProductName() {
		return paramProductName;
	}

	/**
	 * @param paramProductName the paramProductName to set
	 */
	public void setParamProductName(String paramProductName) {
		this.paramProductName = paramProductName;
	}

	/**
	 * @return the paramProductType
	 */
	public String getParamProductType() {
		return paramProductType;
	}

	/**
	 * @param paramProductType the paramProductType to set
	 */
	public void setParamProductType(String paramProductType) {
		this.paramProductType = paramProductType;
	}

	/**
	 * @return the paramProductAttr
	 */
	public String getParamProductAttr() {
		return paramProductAttr;
	}

	/**
	 * @param paramProductAttr the paramProductAttr to set
	 */
	public void setParamProductAttr(String paramProductAttr) {
		this.paramProductAttr = paramProductAttr;
	}

	/**
	 * @return the paramProductIsScm
	 */
	public String getParamProductIsScm() {
		return paramProductIsScm;
	}

	/**
	 * @param paramProductIsScm the paramProductIsScm to set
	 */
	public void setParamProductIsScm(String paramProductIsScm) {
		this.paramProductIsScm = paramProductIsScm;
	}

	/**
	 * @param menuProductIsScm the menuProductIsScm to set
	 */
	public void setMenuProductIsScm(Menu menuProductIsScm) {
		this.menuProductIsScm = menuProductIsScm;
	}

	/**
	 * @return the paramSupplierId
	 */
	public String getParamSupplierId() {
		return paramSupplierId;
	}

	/**
	 * @param paramSupplierId the paramSupplierId to set
	 */
	public void setParamSupplierId(String paramSupplierId) {
		this.paramSupplierId = paramSupplierId;
	}

	/**
	 * @return the paramBrand
	 */
	public String getParamBrand() {
		return paramBrand;
	}

	/**
	 * @param paramBrand the paramBrand to set
	 */
	public void setParamBrand(String paramBrand) {
		this.paramBrand = paramBrand;
	}

	/**
	 * @return the paramHasShelf
	 */
	public String getParamHasShelf() {
		return paramHasShelf;
	}

	/**
	 * @param paramHasShelf the paramHasShelf to set
	 */
	public void setParamHasShelf(String paramHasShelf) {
		this.paramHasShelf = paramHasShelf;
	}

	/**
	 * @return the paramCategoryL1
	 */
	public String getParamCategoryL1() {
		return paramCategoryL1;
	}

	/**
	 * @param paramCategoryL1 the paramCategoryL1 to set
	 */
	public void setParamCategoryL1(String paramCategoryL1) {
		this.paramCategoryL1 = paramCategoryL1;
	}

	/**
	 * @return the paramCategoryL2
	 */
	public String getParamCategoryL2() {
		return paramCategoryL2;
	}

	/**
	 * @param paramCategoryL2 the paramCategoryL2 to set
	 */
	public void setParamCategoryL2(String paramCategoryL2) {
		this.paramCategoryL2 = paramCategoryL2;
	}

	/**
	 * @return the paramCategoryL3
	 */
	public String getParamCategoryL3() {
		return paramCategoryL3;
	}

	/**
	 * @param paramCategoryL3 the paramCategoryL3 to set
	 */
	public void setParamCategoryL3(String paramCategoryL3) {
		this.paramCategoryL3 = paramCategoryL3;
	}

	/**
	 * @return the paramCategoryL4
	 */
	public String getParamCategoryL4() {
		return paramCategoryL4;
	}

	/**
	 * @param paramCategoryL4 the paramCategoryL4 to set
	 */
	public void setParamCategoryL4(String paramCategoryL4) {
		this.paramCategoryL4 = paramCategoryL4;
	}

	/**
	 * @return the menuCategoryLevel1List
	 */
	public List getMenuCategoryLevel1List() {
		if (menuCategoryLevel1List == null) {
			menuCategoryLevel1List = new ArrayList();
		}
		return menuCategoryLevel1List;
	}

	/**
	 * @return the menuCategoryLevel2List
	 */
	public List getMenuCategoryLevel2List() {
		if (menuCategoryLevel2List == null) {
			menuCategoryLevel2List = new ArrayList();
		}
		return menuCategoryLevel2List;
	}

	/**
	 * @return the menuCategoryLevel3List
	 */
	public List getMenuCategoryLevel3List() {
		if (menuCategoryLevel3List == null) {
			menuCategoryLevel3List = new ArrayList();
		}
		return menuCategoryLevel3List;
	}

	/**
	 * @return the menuCategoryLevel4List
	 */
	public List getMenuCategoryLevel4List() {
		if (menuCategoryLevel4List == null) {
			menuCategoryLevel4List = new ArrayList();
		}
		return menuCategoryLevel4List;
	}

	/**
	 * @return the products
	 */
	public List getProducts() {
		return products;
	}

	public String getTmpUseDeliveryDay() {
		return tmpUseDeliveryDay;
	}

	public void setTmpUseDeliveryDay(String tmpUseDeliveryDay) {
		this.tmpUseDeliveryDay = tmpUseDeliveryDay;
	}

	public String getTmpDeliveryDay() {
		return tmpDeliveryDay;
	}

	public void setTmpDeliveryDay(String tmpDeliveryDay) {
		this.tmpDeliveryDay = tmpDeliveryDay;
	}

	public String getExcelPath() {
		return excelPath;
	}

	public void setExcelPath(String excelPath) {
		this.excelPath = excelPath;
	}

	public InputStream getFileInputStream() {
		return fileInputStream;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public int getUploadErr() {
		return uploadErr;
	}

	public void setUploadErr(int uploadErr) {
		this.uploadErr = uploadErr;
	}

	public int getUploadSuccess() {
		return uploadSuccess;
	}

	public String getStep2Upload() {
		return step2Upload;
	}

	public void setStep2Upload(String step2Upload) {
		this.step2Upload = step2Upload;
	}

	public List<String> getErrId() {
		return errId;
	}

	public void setErrId(List<String> errId) {
		this.errId = errId;
	}

	public String getDataoldornew() {
		return dataoldornew;
	}

	public void setDataoldornew(String dataoldornew) {
		this.dataoldornew = dataoldornew;
	}

}
